package com.hnevc.photodemo;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.theartofdev.edmodo.cropper.CropImage;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    private Uri imageUri;
    private Uri resultUri;
    private static final String TAG = "MainActivity";
    private String fileName;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    //takePhoto将在拍照按钮点击后执行
    public void takePhoto(View view) throws IOException {
        //1.准备uri 用来保存拍照数据
        File file = new File(getExternalCacheDir(), "image.jpg");
        if (file.exists()) {
            file.delete();
        }
        file.createNewFile();
        //android4.4可以直接使用fromFile将file转化为Uri，但6.0以上需要使用FileProvider共享文件
        if (Build.VERSION.SDK_INT >= 24) {
            imageUri = FileProvider.getUriForFile(this, "com.hnevc.photodemo.fileprovider", file);
        } else {
            imageUri = Uri.fromFile(file);
        }
        //2.定义Intent，启动拍照程序，然后将数据传回imageUri中
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, 101);

    }
    //

    public void cropPhoto(View view) {
        CropImage.activity(imageUri)
                .start(this);
    }

    //将用户裁切完成的图片上传到服务器
    public void uploadPhoto(View view) {
        //创建一个线程，完成上传数据
        new Thread(new Runnable() {
            @Override
            public void run() {
                //1.从Uri中获取文件对象
                try {
                    String s = resultUri.toString();
                    URI uri = new URI(s);
                    File file = new File(uri);
                    //2.将文件对象构造成RequsestBody
                    RequestBody body = RequestBody.create(MediaType.parse("image/png"), file);
                    //3.将requestbody构造multipartbody
                    MultipartBody.Builder builder=new MultipartBody.Builder();
                    builder.setType(MultipartBody.FORM);
                    builder.addFormDataPart("file","image.jpg",body);
                    MultipartBody multipartBody=builder.build();
                    //4.构造request对象
                    Request request=new Request.Builder()
                            .post(multipartBody)
                            .url("http://10.1.66.232:8080/RestaurantServer/File/doUpload")
                            .build();
                    //5.执行请求
                    OkHttpClient client=new OkHttpClient();
                    Response response = client.newCall(request).execute();
                    String data=response.body().string();
                    JSONObject jsonObject=new JSONObject(data);
                    fileName = jsonObject.getString("realFileName");

                    Log.e(TAG, "run: "+response.code()+data);
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                ;

            }
        }).start();
    }
    public void addFood(View view){
        //1.根据用户输入，构建Food对象
        EditText mEtFoodName= (EditText) findViewById(R.id.id_et_food_name);
        Food food=new Food();
        food.setFoodName(mEtFoodName.getText().toString());
        food.setFoodPrice(2);
        food.setFoodPic(fileName);
        //2.得到上传的字符串
        JSONObject jsonObject=new JSONObject();
        try {
            jsonObject.put("foodName",food.getFoodName());
            jsonObject.put("foodPic",food.getFoodPic());
            jsonObject.put("foodPrice",food.getFoodPrice());

        } catch (JSONException e) {
            e.printStackTrace();
        }

        final String jsons=jsonObject.toString();
        Log.e(TAG, "addFood: "+jsons );
        //使用OKHttp3的post提交表单数据
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client=new OkHttpClient();
                RequestBody requestbody=RequestBody.create(MediaType.parse("application/json"),jsons);
                String url="http://10.1.66.232:8080/RestaurantServer/Food/addFood";
                //构建Request
                Request request=new Request.Builder()
                        .url(url)
                        .post(requestbody)
                        .build();
                try {
                    Response response = client.newCall(request).execute();
                    Log.e(TAG, "run: "+response.body().string() );
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == 101) {
                //拍照成功 将imageUri所指向的文件 显示到imageView中
                try {
                    //从Uri中获取输入流
                    InputStream inputStream = getContentResolver().openInputStream(imageUri);
                    //从输入流获取位图
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    //获取ImageView控件
                    ImageView imageView = (ImageView) findViewById(R.id.id_iv_photp);
                    //在ImageView中显示位图
                    imageView.setImageBitmap(bitmap);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }

            if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
                CropImage.ActivityResult result = CropImage.getActivityResult(data);
                if (resultCode == RESULT_OK) {
                    resultUri = result.getUri();

                    InputStream inputStream = null;
                    try {
                        inputStream = getContentResolver().openInputStream(resultUri);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                    //从输入流获取位图
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    //获取ImageView控件
                    ImageView imageView = (ImageView) findViewById(R.id.id_iv_photp);
                    //在ImageView中显示位图
                    imageView.setImageBitmap(bitmap);

                } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
                    Exception error = result.getError();
                }
            }

        }
    }

}
